//
//  TSBridgeManager+CameraAndAlbum.m
//  dsBridge
//
//  Created by Zac on 2020/10/28.
//

#import "TSBridgeManager+Camera.h"
#import "TSCameraModule.h"

@implementation TSBridgeManager (CameraAndAlbum)



/// 打开拍照并获取图片信息
/// @param completionBlock <#completionBlock description#>
- (void)openCamera:(void(^)(BOOL success,NSString *imageBase64))completionBlock
{
    [TSCameraModule pickImageWithController:self.handleVC sourceType:UIImagePickerControllerSourceTypeCamera allowsEditing:NO completionBlock:^(UIImage * _Nonnull image) {
        
        NSString *imgBase64 = [self getImageBase64Data:image];
        if (imgBase64) {
            completionBlock(YES,imgBase64);
        }
        else
        {
            completionBlock(NO,nil);
        }
    }];
}

/// 打开相册并获取图片信息
/// @param completionBlock <#completionBlock description#>
- (void)openAlbum:(void(^)(BOOL success,NSString *imageBase64))completionBlock
{
    [TSCameraModule pickImageWithController:self.handleVC sourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum allowsEditing:NO completionBlock:^(UIImage * _Nonnull image) {
        NSString *imgBase64 = [self getImageBase64Data:image];
        if (imgBase64) {
            completionBlock(YES,imgBase64);
        }
        else
        {
            completionBlock(NO,nil);
        }

    }];

}

/// 显示菜单并获取图片信息
/// @param completionBlock <#completionBlock description#>
- (void)showMenu:(void(^)(BOOL success,NSString *imageBase64))completionBlock
{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"选择图片"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action)
    {
        [self openCamera:^(BOOL success, NSString * _Nonnull imageBase64) {
            completionBlock(success,imageBase64);
        }];
    }];
    UIAlertAction *album = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action)
    {
        [self openAlbum:^(BOOL success, NSString * _Nonnull imageBase64) {
            completionBlock(success,imageBase64);
        }];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action)
    {
        completionBlock(NO,nil);
    }];

    [alert addAction:camera];
    [alert addAction:album];
    [alert addAction:cancel];


    [self.handleVC presentViewController:alert animated:YES completion:nil];

}


#pragma mark ---------图片管理-----------
//获取图片完整路径
- (NSString *)getImagePath{
    
    NSString* path=NSHomeDirectory();
    path=[path stringByAppendingPathComponent:@"Library/Caches/images"];
    NSFileManager *fm=[NSFileManager defaultManager];
    
    if (![fm fileExistsAtPath:path]) {
        [fm createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg",[self getNowTimestamp]]];
    return filePath;
}

//图片保存本地
- (NSString *)saveImage2Disk:(UIImage *)tempImage
{
    NSData *imageData=UIImageJPEGRepresentation(tempImage, 1);
    // and then we write it out
    NSString *path=[self getImagePath];
    if ([imageData writeToFile:path atomically:YES]) {
        return path;
    }
    return nil;
}

- (NSString *)getNowTimestamp {
    NSDate *date = [NSDate date]; // 获得时间对象
    NSTimeZone *zone = [NSTimeZone systemTimeZone]; // 获得系统的时区
    NSTimeInterval time = [zone secondsFromGMTForDate:date];//以秒为单位返回当前时间与系统格林尼治时间的差
    NSDate *dateNow = [date dateByAddingTimeInterval:time];// 然后把差的时间加上,就是当前系统准确的时间
    long long localTimestamp = (long long)([dateNow timeIntervalSince1970] * 1000);
    return @(localTimestamp).stringValue;
}

- (NSString *)getImageBase64Data:(UIImage *)image
{
    NSData *imagedata = [self getImageCompressionToSpecifiedSize:image];
    NSString *imageBase64 = [imagedata base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    if (imageBase64) {
        return [@"data:image/png;base64," stringByAppendingString:imageBase64];
    }
    return nil;
}

#pragma mark - 图片压缩到指定大小

- (NSData *)getImageCompressionToSpecifiedSize:(UIImage *)image
{
    UIGraphicsBeginImageContext(CGSizeMake(1024, 768));
    [image drawInRect:CGRectMake(0, 0, 1024, 768)];
    UIImage* resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGFloat quality = 1;
    NSData *data = UIImageJPEGRepresentation(resultImage, quality);
    while ((data.length/1024) > 1024 && quality > 0.01f) {
        quality = quality - 0.05;
        data = UIImageJPEGRepresentation(resultImage, quality);
    }
    return data;
}

@end
